import http from '@ohos.net.http'

// import { promptAction } from '@kit.ArkUI';

interface RequestOption {
  isToken?: boolean;
  token?: string;
}

export class Request {
  private instance: http.HttpRequest
  private baseUrl: string
  private isToken: boolean
  private token: string | null

  /**
   * 设置请求类
   * @param baseUrl 请求前缀
   * @param option 请求配置, 若不配置默认添加token, token来自AppStorage,
   */
  constructor(baseUrl = '', option?: RequestOption) {
    this.instance = http.createHttp()
    this.baseUrl = baseUrl
    this.isToken = option?.isToken ?? true
    this.token = option?.token ?? AppStorage.get('token') ?? null


    console.log("<请求, 初始化>设置了BaseUrl, isToken:", this.isToken, "这个时候AppStorage的token为:",
      AppStorage.get('token') || '空?')
  }

  private _request<T>(method: http.RequestMethod, url: string, data: string | Object | ArrayBuffer | undefined,
    option?: http.HttpRequestOptions) {
    console.log("<请求, 发送>当前本地token", AppStorage.get('token') ?? "k")

    const opt: http.HttpRequestOptions = {
      method,
      header: { 'Content-Type': 'application/json' },
      extraData: data
    }

    if (this.token == null) {
      this.token = AppStorage.get('token') ?? null
    }

    if (opt.header && this.isToken) {
      opt.header['X-Auth-Token'] = this.token
      console.log("<请求>当前请求添加了token", this.token)
    } else {
      opt.expectDataType = http.HttpDataType.STRING
      console.log("<请求>当前请求没有添加token", this.token)
    }

    if (option?.header) {
      Object.keys(option.header).forEach((key) => {
        if (opt.header && option.header) {
          opt.header[key] = option.header[key]
        }
      })

      console.log("<请求>添加了请求头:", JSON.stringify(opt.header))
    }

    console.log("<请求>数据:",JSON.stringify(opt,null,4))

    return new Promise<T>((resolve, reject) => {
      console.log("<请求>发请求:\n", this.baseUrl + "\n" + url)
      this.instance.request(this.baseUrl + url, opt, (err, data) => {
        console.log("<请求>请求发出去了")
        if (!err) {
          console.info("<请求>请求没有问题")
          if (!this.isToken) {
            console.log("<请求>设置全局token")
            AppStorage.setOrCreate("token", data.header['x-subject-token'])
            this.token = AppStorage.get('token') || "空?????"
            console.log("<请求>设置全局token成功", AppStorage.get('token'))
          }
          const result = JSON.parse(data.result as string) as T
          resolve(result)
        } else {
          console.log("<请求>请求出错了, err:", JSON.stringify(err.message))
          reject(new Error("<请求>" + err.message))
        }
      })
    })
  }

  get<T>(url: string, options?: Partial<http.HttpRequestOptions>): Promise<T> {
    return this._request<T>(http.RequestMethod.GET, url, options)
  }

  post<T>(url: string, data?: string | Object | ArrayBuffer | undefined, option?: http.HttpRequestOptions): Promise<T> {
    return this._request<T>(http.RequestMethod.POST, url, data, option)
  }
}
